<template>
  <div class="dashboard-editor-container">
    <div>
      <div style="display:flex;justify-content:space-between;">
        <partitionTree :nodeData="nodeData" :expandArray="expandArray" :addTemplate="false" :defaultExpandAll="false"
          @handleNodeClick="handleNodeClick" ref="partitionTree" @toggleVisibility="toggleVisibility">
        </partitionTree>
        <div :style="{ width: containerWidth }" class="box"
          style="background:#fff;border: 1px solid #ddd;border-radius: 4px;box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);">
          <el-row style="background: #fff; padding: 16px 16px 0;">
            <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset">
              <el-button slot="buttonContent" size="small" type="success" style="margin-left: 10px;"
                @click="openPDF">导出PDF</el-button>
            </connsearch>
            <div class="tabclick">
              <div class="tabitem" @click="handleClick()">
                <span><i :class="tab ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
              </div>
            </div>
            <el-row>
              <el-tabs type="border-card" v-if="tab" style="margin-top:16px;" @tab-click="tabClick">
                <el-tab-pane label="按日统计分析" lazy>
                  <el-row :gutter="20">
                    <el-col :xs="24" :sm="24" :lg="24">
                      <eventTrends :chartData="barchartData1" @barclick="echartsClick" title="按日统计分析" />
                    </el-col>
                  </el-row>
                </el-tab-pane>
                <el-tab-pane label="按资产名称统计分析" lazy>
                  <el-col :xs="24" :sm="24" :lg="24">
                    <eventTrends :chartData="barchartData2" @barclick="echartsClick" title="按资产名称统计分析" />
                  </el-col>
                </el-tab-pane>
                <el-tab-pane label="按部门时长统计分析" lazy>
                  <el-col :xs="24" :sm="24" :lg="24">
                    <eventTrends :chartData="barchartData3" @barclick="echartsClick" title="按部门时长统计分析" />
                  </el-col>
                </el-tab-pane>
                <el-tab-pane label="按时长类型统计分析" lazy>
                  <el-col :xs="24" :sm="24" :lg="24">
                    <piechart :chartData="pie1Data" @pieclick="echartsClick" title="按时长类型统计分析" />
                  </el-col>
                </el-tab-pane>
              </el-tabs>
            </el-row>
            <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :lg="{ span: 24 }" :xl="{ span: 24 }"
              style="padding-right: 8px;margin:16px 0;">
              <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
                <el-table-column label="序号" width="60" type="index"
                  :index='(index) => { return (index + 1) + (this.pageNum - 1) * this.pageSize }'> </el-table-column>
                <el-table-column label="部门" show-overflow-tooltip prop="Department" width="120px"></el-table-column>
                <el-table-column label="资产名称" show-overflow-tooltip prop="DeviceName" width="160px"></el-table-column>
                <el-table-column label="使用者" show-overflow-tooltip prop="UserName" width="120px"></el-table-column>
                <el-table-column label="活跃时长" prop="ActiveTime" :formatter="formatDuration"
                  show-overflow-tooltip></el-table-column>
                <el-table-column label="屏保时长" prop="ScreenSaverTime" :formatter="formatDuration"
                  show-overflow-tooltip></el-table-column>
                <el-table-column label="锁屏时长" prop="LockedTime" :formatter="formatDuration"
                  show-overflow-tooltip></el-table-column>
                <el-table-column label="离开时长" prop="IdleTime" :formatter="formatDuration"
                  show-overflow-tooltip></el-table-column>
                <el-table-column label="总运行时长" prop="TotalTime" :formatter="formatDuration"
                  show-overflow-tooltip></el-table-column>
                <!-- <el-table-column label="操作" width="120px" fixed="right">
                  <template slot-scope="scope">
                    <el-button size="mini" type="primary" @click="changeMailGlobal(scope.row)">最近日志</el-button>
                  </template>
                </el-table-column> -->
              </el-table>
              <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page=pageNum
                :page-size=pageSize background layout="total, prev, pager, sizes, next, jumper" :total="total">
              </el-pagination>
            </el-col>
          </el-row>
          <el-dialog top="5vh" :close-on-click-modal="false" :close-on-press-escape=false title="最近日志"
            :visible.sync="logDialog" v-el-drag-dialog width="80%">
            <el-table stripe border :data="logList" style="width: 100%; margin-top: 15px">
              <el-table-column label="序号" width="60" type="index"
                :index='(index) => { return (index + 1) + (this.pageNum - 1) * this.pageSize }'> </el-table-column>
              <el-table-column label="部门" show-overflow-tooltip prop="Department" width="120px"></el-table-column>
              <el-table-column label="资产名称" show-overflow-tooltip prop="DeviceName" width="160px"></el-table-column>
              <el-table-column label="使用者" show-overflow-tooltip prop="UserName" width="120px"></el-table-column>
              <el-table-column label="活跃时长" prop="ActiveTime" :formatter="formatDuration"
                show-overflow-tooltip></el-table-column>
              <el-table-column label="屏保时长" prop="ScreenSaverTime" :formatter="formatDuration"
                show-overflow-tooltip></el-table-column>
              <el-table-column label="锁屏时长" prop="LockedTime" :formatter="formatDuration"
                show-overflow-tooltip></el-table-column>
              <el-table-column label="离开时长" prop="IdleTime" :formatter="formatDuration"
                show-overflow-tooltip></el-table-column>
              <el-table-column label="总运行时长" prop="TotalTime" :formatter="formatDuration"
                show-overflow-tooltip></el-table-column>
            </el-table>
            <el-pagination @size-change="handleSizeChange2" @current-change="handleCurrentChange2" :current-page=pageNum2
              :page-size=pageSize2 background layout="total, prev, pager, sizes, next, jumper" :total="total2">
            </el-pagination>
            <span slot="footer" class="dialog-footer">
              <el-button type="info" @click="logDialog = false">关 闭</el-button>
            </span>
          </el-dialog>
          <el-dialog :close-on-click-modal="false" :close-on-press-escape=false :barchartData1="barchartData1" top="3vh"
            :barchartData2="barchartData2" :barchartData3="barchartData3" :pieData="pie1Data" :tableData="tableData"
            :visible.sync="pdfDialog" title="PDF打印" v-el-drag-dialog width="80%">
            <div style="height: calc(100vh - 200px); overflow-y: auto;">
              <div ref="pdfContent" style="padding: 20px">
                <p style="text-align: left;font-size: 20px;font-weight: 600;" class="title">按日统计分析</p>
                <eventTrends :chartData="barchartData1" title="按日统计分析" />
                <p style="text-align: left;font-size: 20px;font-weight: 600;" class="title">按资产名称统计分析</p>
                <eventTrends :chartData="barchartData2" title="按资产名称统计分析" />
                <p style="text-align: left;font-size: 20px;font-weight: 600;" class="title">按部门时长统计分析</p>
                <eventTrends :chartData="barchartData3" title="按部门时长统计分析" />
                <p style="text-align: left;font-size: 20px;font-weight: 600;" class="title">按时长类型统计分析</p>
                <piechart :chartData="pie1Data" title="按时长类型统计分析" />
                <p style="text-align: left;font-size: 20px;font-weight: 600;margin-top: 50px;" class="title">电脑使用列表</p>
                <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
                  <el-table-column label="序号" width="60" type="index"
                    :index='(index) => { return (index + 1) + (this.pageNum - 1) * this.pageSize }'> </el-table-column>
                  <el-table-column label="部门" show-overflow-tooltip prop="Department" width="120px"></el-table-column>
                  <el-table-column label="资产名称" show-overflow-tooltip prop="DeviceName" width="160px"></el-table-column>
                  <el-table-column label="使用者" show-overflow-tooltip prop="UserName" width="120px"></el-table-column>
                  <el-table-column label="活跃时长" prop="ActiveTime" :formatter="formatDuration"
                    show-overflow-tooltip></el-table-column>
                  <el-table-column label="屏保时长" prop="ScreenSaverTime" :formatter="formatDuration"
                    show-overflow-tooltip></el-table-column>
                  <el-table-column label="锁屏时长" prop="LockedTime" :formatter="formatDuration"
                    show-overflow-tooltip></el-table-column>
                  <el-table-column label="离开时长" prop="IdleTime" :formatter="formatDuration"
                    show-overflow-tooltip></el-table-column>
                  <el-table-column label="总运行时长" prop="TotalTime" :formatter="formatDuration"
                    show-overflow-tooltip></el-table-column>
                </el-table>
              </div>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="exportPDF">打 印</el-button>
              <el-button type="info" @click="pdfDialog = false">关 闭</el-button>
            </span>
          </el-dialog>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import connsearch from "@/components/connSearch";
import partitionTree from "@/components/partitionTree";
import eventTrends from './components/barchart.vue'  //柱状图
import piechart from "./components/piechart.vue";
import EChartsAndTableToPDF from "./components/EChartsAndTableToPDF.vue";
import { GetDeviceTree, parseTime, formatDuration, findValueByKey } from "@/utils/index.js";
import { connrequest } from "@/api/firstPage.js"
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';
export default {
  directives: { elDragDialog },
  components: { connsearch, eventTrends, piechart, partitionTree, EChartsAndTableToPDF },
  data() {
    let that = this
    return {
      activeName: "",
      tabTitle: '按日统计分析',
      pageNum: 1,
      pageSize: 10,
      total: 0,
      pageNum2: 1,
      pageSize2: 10,
      total2: 0,
      logList: [],
      containerWidth: 'calc(100% - 275px)',
      tab: false,
      pdfDialog: false,
      logDialog: false,
      nodeData: [],
      DepartmentList: [],
      DeviceList: [],
      expandArray: [0, 100],
      barchartData1: { xAxis: [], series: [] },
      barchartData2: { xAxis: [], series: [] },
      barchartData3: { xAxis: [], series: [] },
      pie1Data: [],
      tableData: [],
      searchform: {},
      options: {},
      nodeobj: {},
      searchobj: {},
      echartsobj: {},
      formOptions: [
        {
          col: 10,
          hidden: false,
          label: "日期", // label文字
          prop: "timeRange", // 字段名
          initValue: [], // 字段初始值,
          element: "el-date-picker", // 指定elementui组件
          events: {
            input(val) {
              that.searchform.timeRange = val
            }
          }
        },
      ]
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = (Cookies.get('Zhuoguan_DefaultPageLength') || 10) * 1;

    let endTime = new Date(new Date().setHours(0, 0, 0, 0)).getTime()
    let startTime = endTime - ((Cookies.get('Zhuoguan_DefaultLogDays') || 7) * 24 * 3600 * 1000);
    let arr = [parseTime(startTime), '']
    this.formOptions.map(item => {
      if (item.label === '日期') {
        item.initValue = arr
      }
    })
    this.$set(this.searchform, 'timeRange', arr)
    this.$set(this.searchform, 'Status', 0)
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.initData()
  },
  methods: {
    parseTime,
    formatDuration(row, column, value) {
      if (column.property === 'TotalTime' || !row.TotalTime) return formatDuration(value);
      return `${formatDuration(value)} (${((value / row.TotalTime) * 100).toFixed(1)}%)`;
    },
    async initData(searchobj = {}) {
      try {
        const { DeviceTree, departments, devices } = await GetDeviceTree()
        this.nodeData = DeviceTree
        this.DepartmentList = departments
        this.DeviceList = devices
        this.expandArray = [DeviceTree?.[0]?.Name]
      } catch (error) {
        this.$message.error('加载设备树数据失败');
      }
    },
    handleNodeClick(nodeData) {
      this.pageNum = 1
      this.nodeobj = { DepartmentID: nodeData.data.isDevice ? nodeData.data.DepartmentID : nodeData.data.ID, DeviceUUID: nodeData.data.isDevice ? nodeData.data.DeviceUUID : '' }
      this.echartsobj = {}
      this.getData({ ...this.searchobj, ...this.nodeobj })
    },
    toggleVisibility(isHidden) {
      if (isHidden)
        this.containerWidth = '100%';
      else
        this.containerWidth = 'calc(100% - 275px)';
    },
    async openPDF() {
      this.GetEventLog({ ...this.searchobj, ...this.nodeobj, ...this.echartsobj })
      this.GetAgentActiveTimeSumGroupByDate({ ...this.searchobj, ...this.nodeobj, ...this.echartsobj })
      this.GetAgentActiveTimeSumGroupByDevice({ ...this.searchobj, ...this.nodeobj, ...this.echartsobj })
      this.GetAgentActiveTimeSumGroupByTimetype({ ...this.searchobj, ...this.nodeobj, ...this.echartsobj })
      this.GetAgentActiveTimeSumGroupByDepartment({ ...this.searchobj, ...this.nodeobj, ...this.echartsobj })
      this.pdfDialog = true
    },
    async exportPDF() {
      const element = this.$refs.pdfContent
      const canvas = await html2canvas(element, {
        scale: window.devicePixelRatio, // 提高分辨率
        useCORS: true // 如果有图片，开启跨域
      })
      const imgData = canvas.toDataURL('image/png')
      const pdf = new jsPDF('p', 'mm', 'a4')
      const pageWidth = pdf.internal.pageSize.getWidth()
      const pageHeight = pdf.internal.pageSize.getHeight()
      const imgWidth = pageWidth
      const imgHeight = (canvas.height / canvas.width) * imgWidth
      // 如果内容超出一页，添加分页
      let position = 0
      if (imgHeight < pageHeight) {
        pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight)
      } else {
        while (position < imgHeight) {
          pdf.addImage(imgData, 'PNG', 0, -position, imgWidth, imgHeight)
          position += pageHeight
          if (position < imgHeight) pdf.addPage()
        }
      }
      pdf.save('电脑使用统计文件.pdf')
    },
    // 获取所有数据
    async getData(searchobj = {}) {
      this.GetEventLog(searchobj)
      switch (this.tabTitle) {
        case '按日统计分析':
          this.GetAgentActiveTimeSumGroupByDate(searchobj)
          break;
        case '按资产名称统计分析':
          this.GetAgentActiveTimeSumGroupByDevice(searchobj)
          break;
        case '按时长类型统计分析':
          this.GetAgentActiveTimeSumGroupByTimetype(searchobj)
          break;
        case '按部门时长统计分析':
          this.GetAgentActiveTimeSumGroupByDepartment(searchobj)
          break;
      }
    },
    async echartsClick(val, title) {
      this.pageNum = 1
      if (title === '按日统计分析') {
        this.echartsobj = { StartTime: `${val} 00:00:00`, EndTime: `${val} 23:59:59` }
        this.GetEventLog({ ...this.searchobj, ...this.nodeobj, ...this.echartsobj })
      } else if (title === '按资产名称统计分析') {
        this.echartsobj = { DeviceUUID: findValueByKey(val, this.DeviceList, 'DeviceName', 'DeviceUUID') }
        this.GetEventLog({ ...this.searchobj, ...this.nodeobj, ...this.echartsobj })
      } else if (title === '按时长类型统计分析') {
        this.echartsobj = { DeviceName: val }
        this.GetEventLog({ ...this.searchobj, ...this.nodeobj, ...this.echartsobj })
      } else if (title === '按部门时长统计分析') {
        this.echartsobj = { DepartmentID: findValueByKey(val, this.DepartmentList, 'Name', 'ID') }
        this.GetEventLog({ ...this.searchobj, ...this.nodeobj, ...this.echartsobj })
      }
    },
    tabClick(row) {
      this.tabTitle = row.label
      switch (row.label) {
        case '按日统计分析':
          this.GetAgentActiveTimeSumGroupByDate({ ...this.searchobj, ...this.nodeobj })
          break;
        case '按资产名称统计分析':
          this.GetAgentActiveTimeSumGroupByDevice({ ...this.searchobj, ...this.nodeobj })
          break;
        case '按时长类型统计分析':
          this.GetAgentActiveTimeSumGroupByTimetype({ ...this.searchobj, ...this.nodeobj })
          break;
        case '按部门时长统计分析':
          this.GetAgentActiveTimeSumGroupByDepartment({ ...this.searchobj, ...this.nodeobj })
          break;
      }
    },
    async changeMailGlobal(row) {
      this.DeviceUUID = row.DeviceUUID
      this.DepartmentID = row.DepartmentID
      this.pageNum2 = row.pageNum || 1
      const data = {
        Paging: {
          QueryPageNo: row.pageNum || 1,
          QueryPageLength: this.pageSize2
        },
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          DeviceUUID: row.DeviceUUID,
          DepartmentID: row.DepartmentID
        }
      }
      const res = await connrequest('GetAgentActiveTimeDetail', data)
      res.Data = res.Data.map(item => {
        item.TransTime = parseTime(item.TransTime)
        return item
      })
      this.logList = res.Data
      this.total2 = res.Paging?.TotalCount
      this.logDialog = true
    },
    // 获取事件日志列表
    async GetEventLog(searchobj = {}) {
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          DeviceUUID: this.searchform.DeviceUUID || '',
          DepartmentID: this.searchform.DepartmentID || '',
          ...searchobj
        }
      }
      const res = await connrequest('GetAgentActiveTime', data)
      res.Data = res.Data || []
      this.tableData = res.Data
      this.total = res.Paging.TotalCount
    },
    // 获取事件日期统计
    async GetAgentActiveTimeSumGroupByDate(searchobj = {}) {
      let xAxis = []
      let t1 = []
      let t2 = []
      let t3 = []
      let t4 = []
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          DeviceUUID: this.searchform.DeviceUUID || '',
          DepartmentID: this.searchform.DepartmentID || '',
          ...searchobj
        }
      }
      const res = await connrequest('GetAgentActiveTimeSumGroupByDate', data)
      res.Data = res.Data || []
      res.Data.map(item => {
        xAxis.push(item.TransDate)
        t1.push(item.ActiveTime)
        t2.push(item.ScreenSaverTime)
        t3.push(item.LockedTime)
        t4.push(item.IdleTime)
      })
      this.barchartData1 = { xAxis, t1, t2, t3, t4 }
    },
    // 按资产名称统计分析
    async GetAgentActiveTimeSumGroupByDevice(searchobj = {}) {
      let xAxis = []
      let t1 = []
      let t2 = []
      let t3 = []
      let t4 = []
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          DeviceUUID: this.searchform.DeviceUUID || '',
          DepartmentID: this.searchform.DepartmentID || '',
          ...searchobj
        }
      }
      const res = await connrequest('GetAgentActiveTimeSumGroupByDevice', data)
      res.Data = res.Data || []
      res.Data.map(item => {
        xAxis.push(item.DeviceName)
        t1.push(item.ActiveTime)
        t2.push(item.ScreenSaverTime)
        t3.push(item.LockedTime)
        t4.push(item.IdleTime)
      })
      this.barchartData2 = { xAxis, t1, t2, t3, t4 }
    },
    // 按部门时长统计分析
    async GetAgentActiveTimeSumGroupByDepartment(searchobj = {}) {
      let xAxis = []
      let t1 = []
      let t2 = []
      let t3 = []
      let t4 = []
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          DeviceUUID: this.searchform.DeviceUUID || '',
          DepartmentID: this.searchform.DepartmentID || '',
          ...searchobj
        }
      }
      const res = await connrequest('GetAgentActiveTimeSumGroupByDepartment', data)
      res.Data = res.Data || []
      res.Data.map(item => {
        xAxis.push(item.Department)
        t1.push(item.ActiveTime)
        t2.push(item.ScreenSaverTime)
        t3.push(item.LockedTime)
        t4.push(item.IdleTime)
      })
      this.barchartData3 = { xAxis, t1, t2, t3, t4 }
    },
    // 按时长类型统计分析
    async GetAgentActiveTimeSumGroupByTimetype(searchobj = {}) {
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          DeviceUUID: this.searchform.DeviceUUID || '',
          DepartmentID: this.searchform.DepartmentID || '',
          ...searchobj
        }
      }
      const res = await connrequest('GetAgentActiveTimeSumGroupByTimetype', data)
      this.pie1Data = [
        { name: '活跃时长', value: res.Data[0].ActiveTime || 0 },
        { name: '屏保时长', value: res.Data[0].ScreenSaverTime || 0 },
        { name: '锁屏时长', value: res.Data[0].LockedTime || 0 },
        { name: '离开时长', value: res.Data[0].IdleTime || 0 },
      ]
    },
    // 搜索
    search(val) {
      this.pageNum = 1
      this.searchobj = { ...val }
      this.searchform = { ...val }
      if (this.searchform.timeRange) {
        this.searchobj = { ...this.searchobj, StartTime: this.searchform?.timeRange[0] || '', EndTime: this.searchform?.timeRange[1] || '' }
      }
      this.getData({ ...this.echartsobj, ...this.searchobj, ...this.nodeobj })
      this.initData({ ...this.searchobj })
    },
    // 重置
    reset() {
      let endTime = new Date(new Date().setHours(0, 0, 0, 0)).getTime()
      let startTime = endTime - ((Cookies.get('Zhuoguan_DefaultLogDays') || 7) * 24 * 3600 * 1000);
      let arr = [parseTime(startTime), '']
      this.pageNum = 1
      this.formOptions = this.formOptions.map(item => {
        if (item.label === "日期") {
          item.initValue = arr
        } else if (item.label === "状态变更") {
          item.initValue = 0
        } else {
          item.initValue = ""
        }
        return item
      })
      this.searchform = {}
      this.echartsobj = {}
      this.searchobj = {}
      this.nodeobj = {}
      this.$set(this.searchform, 'timeRange', arr)
      this.$set(this.searchform, 'Status', 0)
      this.$refs.connsearch.addInitValue()
      this.getData()
      this.initData()
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.pageNum = 1
      this.GetEventLog({ ...this.searchobj, ...this.echartsobj, ...this.nodeobj })
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.GetEventLog({ ...this.searchobj, ...this.echartsobj, ...this.nodeobj })
    },
    handleSizeChange2(pageSize) {
      this.pageSize2 = pageSize
      this.pageNum2 = 1
      this.changeMailGlobal({ ...this.searchobj, ...this.echartsobj, ...this.nodeobj, DeviceUUID: this.DeviceUUID, DepartmentID: this.DepartmentID, pageNum: this.pageNum2 })
    },
    handleCurrentChange2(pageNum) {
      this.pageNum2 = pageNum
      this.changeMailGlobal({ ...this.searchobj, ...this.echartsobj, ...this.nodeobj, DeviceUUID: this.DeviceUUID, DepartmentID: this.DepartmentID, pageNum: pageNum })
    },
    handleClick() {
      this.tab = !this.tab
    }
  }
};
</script>
<style lang="scss" scoped>
@import "./components/css/conncss.scss";
</style>